<template>
  <div>
    <div class="header w-full bg-white flex justify-between">
      <BasicForm @register="registerForm" />
      <div>
        <Button
          type="primary"
          :icon="h(FileTextFilled)"
          class="float-right mr-2 mt-2.5"
          @click="handleSave"
          :loading="loading"
          ghost
        >
          保存
        </Button>
        <!-- <Button
          type="primary"
          :icon="h(EditOutlined)"
          class="float-right mr-2 mt-2.5"
          @click="handleEdit"
          :loading="loading"
          ghost
        >
          编辑
        </Button> -->
      </div>
    </div>
    <div class="w-full flex">
      <div class="w-4/5 mt-4" :style="{ height: 'calc(100vh - 80px - 36px - 70px)' }">
        <div class="h-12 p-4 bg-white border-b-1 border-[#ebebeb] font-medium base-font-85">
          预览图
        </div>
        <component
          class=""
          :style="{ height: 'calc(100% - 48px)' }"
          :is="tabs[fqn]"
          :widgetData="widgetData"
        />
      </div>
      <div
        class="mt-4 ml-4 bg-white"
        :style="{ height: 'calc(100vh - 80px - 36px - 70px)', width: 'calc(20% - 32px)' }"
      >
        <PublicSetting
          v-if="fqn"
          :fqn="fqn"
          :whereFrom="whereFrom"
          :formData="formData"
          @success="handleSuccess"
        />
      </div>
    </div>
    <PublicSettingModal :fqn="fqn" @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
  import { FileTextFilled } from '@ant-design/icons-vue';
  import { Button } from 'ant-design-vue';
  import { onMounted, h, ref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useRouter } from 'vue-router';
  import { tabs, switchType, getExampleData } from './index.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getWidgetByFqn,
    saveWidgetInfo,
    getWidgetById,
  } from '/@/api/thingsborad/resources/widgets/widgets';
  import PublicSettingModal from '/@/views/thingsborad/dashboards/components/ConfigureDashboard/components/PublicSettingModal.vue';
  import PublicSetting from './PublicSetting.vue';
  import { useModal } from '/@/components/Modal';

  const router = useRouter();
  const loading = ref<boolean>(false);
  // 部件类型
  const fqn = ref<string>('');
  // 部件绘制页面的打开方式
  const mode = ref<string>('');
  // 表单数据
  const formData = ref<any>();
  // 部件信息
  const widgetInfo = ref<any>();
  // 操作来路
  const whereFrom = ref<any>('');
  // 渲染的数据
  const widgetData = ref<Recordable>();
  const { createMessage } = useMessage();
  const [registerModal, {}] = useModal();
  const [registerForm, { validate, setFieldsValue }] = useForm({
    schemas: [
      {
        field: 'title',
        label: '',
        component: 'Input',
        componentProps: {
          placeholder: '请输入部件名称',
        },
        colProps: {
          style: {
            marginLeft: '16px',
            marginTop: '10px',
          },
        },
        required: true,
      },
    ],
    showActionButtonGroup: false,
  });

  // 最终保存部件数据
  const handleSave = async () => {
    const { title } = await validate();
    let params = {};
    widgetInfo.value.descriptor.defaultConfig = JSON.stringify(formData.value);
    if (mode.value == 'add') {
      params = {
        deprecated: false,
        descriptor: widgetInfo.value.descriptor,
        name: title,
      };
      await saveWidgetInfo(params);
      createMessage.success('配置保存成功');
      loading.value = false;
    } else if (mode.value == 'edit') {
      delete widgetInfo.value.externalId;
      delete widgetInfo.value.tenantId;
      await saveWidgetInfo(widgetInfo.value);
      createMessage.success('配置保存成功');
      loading.value = false;
    }
  };

  function handleSuccess(_randomId: string, values: Recordable) {
    formData.value = getExampleData[fqn.value](values); //value
    widgetData.value = getExampleData[fqn.value](values);
  }

  // function handleEdit() {
  //   if (mode.value == 'add') {
  //     openModal(true, {
  //       whereFrom: 'widgetsLibrary',
  //     });
  //   } else if (mode.value == 'edit') {
  //     openModal(true, {
  //       whereFrom: 'widgetsLibrary',
  //       formData: formData.value,
  //     });
  //   }
  // }

  onMounted(async () => {
    let a =
      '{"datasources":[{"type":"function","name":"function","dataKeys":[{"name":"f(x)","type":"function","label":"Random","color":"#2196f3","settings":{},"_hash":0.15479322438769105,"funcBody":"var value = prevValue + Math.random() * 100 - 50;\\nvar multiplier = Math.pow(10, 2 || 0);\\nvar value = Math.round(value * multiplier) / multiplier;\\nif (value < -1000) {\\n\\tvalue = -1000;\\n} else if (value > 1000) {\\n\\tvalue = 1000;\\n}\\nreturn value;"}]}],"timewindow":{"realtime":{"timewindowMs":60000}},"showTitle":true,"backgroundColor":"#fff","color":"rgba(0, 0, 0, 0.87)","padding":"8px","settings":{},"title":"Attributes card"}';
    console.log(JSON.parse(a), 'aaaaaa');

    const { key, type, widgetId } = router.currentRoute.value.query;
    mode.value = key as string;
    whereFrom.value = 'widgetsLibrary';
    if (mode.value == 'add') {
      fqn.value = type as string;
      console.log(fqn.value, 'fqn.value');

      widgetInfo.value = await getWidgetByFqn({ fqn: 'system.' + fqn.value });
      console.log(widgetInfo.value, 'widgetInfo.value');

      /* openModal(true, {
        whereFrom: 'widgetsLibrary',
      }); */
    } else if (mode.value == 'edit') {
      widgetInfo.value = await getWidgetById(widgetId as string);
      fqn.value = switchType(widgetInfo.value.descriptor.type);
      setFieldsValue({
        title: widgetInfo.value.name,
      });
      formData.value = JSON.parse(widgetInfo.value.descriptor.defaultConfig);
      widgetData.value = getExampleData[fqn.value](
        JSON.parse(widgetInfo.value.descriptor.defaultConfig),
      );
    }
  });
</script>
